<?php
define ( "PERM_USER", 0 );
define ( "PERM_GROUP", 1 );

class PermsManager 
{
	var $dbm;
	var $sess;

	function PermsManager ( & $dbm, & $sess )
	{
		$this->dbm = & $dbm;
		$this->sess = & $sess;
	}
	
	function & read_user ( $mod_name, $uid = 0 )
	{
		if ( ! $uid ) $uid = $this->sess->get ( "uid" );
		if ( ! $uid )
		{
			$vals = array ();
			return $vals;
		}

		$sql = "SELECT perms FROM user_perm WHERE uid=$uid AND module_name='$mod_name'";
		error_log ( $sql );
		$vals = & $this->_retrieve_perms ( $sql );

		return $vals;
	}

	function & read_group ( $mod_name, $gid )
	{
		$sql = "SELECT perms FROM user_group_perm WHERE gid=$gid AND module_name='$mod_name'";
		$vals = & $this->_retrieve_perms ( $sql );

		return $vals;
	}

	function write_user ( & $perms, $mod_name, $uid = 0 )
	{
		if ( ! $uid ) $uid = $this->sess->get ( "uid" );

		$this->_write_perms ( & $perms, $mod_name,  $uid, PERM_USER );
	}

	function write_group ( & $perms, $mod_name, $gid = 0 )
	{
		$this->_write_perms ( & $perms, $mod_name,  $gid, PERM_GROUP );
	}

	function & add_group ( & $user_perms, & $group_perms )
	{
		foreach ( $group_perms as $perm_name => $val )
		{
			if ( array_key_exists ( $perm_name, $user_perms ) ) continue;

			$user_perms [ $perm_name ] = 2;
		}

		return $user_perms;
	}

	function & del_group ( & $user_perms, & $group_perms )
	{
		foreach ( $group_perms as $perm_name => $val )
			if ( @ $user_perms [ $perm_name ] == 2 ) unset ( $user_perms [ $perm_name ] );

		return $user_perms;
	}

	function & _retrieve_perms ( $sql )
	{ 
		$v = & $this->dbm->single_row ( $sql );

		if ( $v )
			$vals = unserialize ( $v [ 'perms' ] );
		else 
			$vals = array ();

		return $vals;
	}

	function _write_perms ( & $perms, $mod_name, $id, $mode = PERM_USER )
	{
		$p = addslashes ( serialize ( $perms ) );

		if ( $mode == PERM_USER )
		{
			$idf = "uid";
			$tab = "user_perm";
		} else {
			$idf = "gid";
			$tab = "user_group_perm";
		}

		$sql = "REPLACE INTO $tab ( $idf, module_name, perms ) VALUES ( $id, '$mod_name', '$p' )";
		$this->dbm->exec ( $sql );
	}
}
?>
